package com.why.rpc.core.common.loadbalance;

import com.alibaba.nacos.api.naming.pojo.Instance;

import lombok.extern.slf4j.Slf4j;
import com.why.rpc.core.common.enums.ErrorEnum;
import com.why.rpc.core.common.exception.RpcException;

import java.util.List;

/**
 * @program: whyrpcframework
 * @description:
 * @author: @why
 * @create: 2021-03-14 10:06
 **/
@Slf4j
public class RoundRobinLoadBalancer implements LoadBalancer {
    private static int index = 0;

    @Override
    public Instance selectInstance(List<Instance> instances) {

        log.info("使用轮转算法");

        /**
         * 假设使用4个服务器，此时index默认为0
         */
        if(instances.size()==0){
            throw new RpcException(ErrorEnum.NO_SERVICE_AVIAILABLE);
        }
        index=index%instances.size();
        Instance instance = instances.get(index);
        index=index+1;
         return  instance;
    }


}
